package com.nidu.demo.config.gatewayimpl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nidu.demo.config.convertor.ConfigConvertor;
import com.nidu.demo.config.gateway.ConfigGateway;
import com.nidu.demo.config.mapper.ConfigMapper;
import com.nidu.demo.config.mapper.dataobject.ConfigDO;
import com.nidu.demo.config.model.Config;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.List;

/**
 * 系统配置网关实现类
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class ConfigGatewayImpl implements ConfigGateway {

    private final ConfigMapper mapper;
    private final ConfigConvertor convertor;

    @Override
    public Config create(Config config) {
        ConfigDO configDO = convertor.toDataObject(config);
        mapper.insert(configDO);
        return convertor.toDomainObject(configDO);
    }

    @Override
    public Config update(Config config) {
        ConfigDO configDO = convertor.toDataObject(config);
        mapper.updateById(configDO);
        return convertor.toDomainObject(configDO);
    }

    @Override
    public Config getById(Long id) {
        ConfigDO configDO = mapper.selectById(id);
        if (configDO == null) {
            return null;
        }
        return convertor.toDomainObject(configDO);
    }

    @Override
    public Config getByKey(String key) {
        ConfigDO configDO = mapper.selectByKey(key);
        if (configDO == null) {
            return null;
        }
        return convertor.toDomainObject(configDO);
    }

    @Override
    public List<Config> getByNameLike(String name) {
        List<ConfigDO> configDOS = mapper.selectByNameLike(name);
        return convertor.toDomainObjects(configDOS);
    }

    @Override
    public List<Config> getByStatus(Integer status) {
        List<ConfigDO> configDOS = mapper.selectByStatus(status);
        return convertor.toDomainObjects(configDOS);
    }

    @Override
    public List<Config> getPage(Integer pageNum, Integer pageSize) {
        Page<ConfigDO> page = new Page<>(pageNum, pageSize);
        Page<ConfigDO> result = mapper.selectPage(page, new LambdaQueryWrapper<>());
        return convertor.toDomainObjects(result.getRecords());
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteById(id);
    }

    @Override
    public void deleteByIds(Set<Long> ids) {
        if (CollUtil.isNotEmpty(ids)) {
            mapper.deleteBatchIds(ids);
        }
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        ConfigDO configDO = new ConfigDO();
        configDO.setId(id);
        configDO.setStatus(status);
        mapper.updateById(configDO);
    }
} 